package com.levi.juc.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * BolckingQueue的   四种Api
 */
public class BolckingQueueTest {

    public static void main(String[] args) throws InterruptedException {
//        test1();
//        test2();
//        test3();
        test4();
    }

    /**
     * 有返回值，抛出异常
     * add的时候超出队列的长度，就会报错 .IllegalStateException
     * remove的时候，队列里面没有元素也会报错
     */
    public static void test1() {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        System.out.println(queue.add("a"));
        System.out.println(queue.add("b"));
        System.out.println(queue.add("c"));
        //超出队列的长度，就会报错 .IllegalStateException
//        System.out.println(queue.add("d"));
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.remove());//报错
    }

    /**
     * 有返回值，不抛出异常
     * offer()方法   队列满的时候再添加元素会返回false
     * poll()方法    队列为空的时候，remove元素会返回null
     */
    public static void test2() {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        System.out.println(queue.offer("a"));
        System.out.println(queue.offer("b"));
        System.out.println(queue.offer("c"));
        System.out.println(queue.offer("d"));
        System.out.println("******");

        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }

    /**
     * 等待阻塞,队列满了再往里面添加元素程序会一直阻塞到那里
     */
    public static void test3() throws InterruptedException {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        queue.put("a");
        queue.put("b");
        queue.put("c");
        //再往里面添加元素会一直阻塞到那里
//        queue.put("d");


        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
        //没有元素了，这时候再take程序会一直阻塞在那里
        System.out.println(queue.take());
    }

    /**
     * 超时等待
     */
    public static void test4() throws InterruptedException {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        System.out.println(queue.offer("a", 2, TimeUnit.SECONDS));
        System.out.println(queue.offer("b", 2, TimeUnit.SECONDS));
        System.out.println(queue.offer("c", 2, TimeUnit.SECONDS));
        //队列满了，这时候 再往里面添加元素，添加不进去，再等待2s还是添加不进去就直接返回false
        System.out.println(queue.offer("d", 2, TimeUnit.SECONDS));
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>");
        System.out.println(queue.poll(2, TimeUnit.SECONDS));
        System.out.println(queue.poll(2, TimeUnit.SECONDS));
        System.out.println(queue.poll(2, TimeUnit.SECONDS));
        //这时候队列中没有元素，再poll的时候会等待2s，还是没有元素进来就直接返回null
        System.out.println(queue.poll(2, TimeUnit.SECONDS));
    }
}
